import axios from 'axios'
import {
  MessageBox
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth/token'
import {
  getCookieValue
} from '@/utils/utils'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 1800000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    addXRequestedWithHeader(config.headers);
    addAuthorizationHeaders(config.headers);
    addAspNetCoreCultureHeader(config.headers);
    addAcceptLanguageHeader(config.headers);
    addTenantIdHeader(config.headers);
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

function addXRequestedWithHeader(headers) {
  if (headers) {
    headers = headers['X-Requested-With'] = 'XMLHttpRequest';
  }
}

function addAuthorizationHeaders(headers) {
  const token = getToken();
  if (store.getters.token && token && headers && !headers.hasOwnProperty('Authorization')) {
    headers['Authorization'] = token;
  }
}

function addAspNetCoreCultureHeader(headers) {
  const cookieLangValue = getCookieValue("Abp.Localization.CultureName");
  if (cookieLangValue && headers && !headers.hasOwnProperty('.AspNetCore.Culture')) {
    headers['.AspNetCore.Culture'] = cookieLangValue;
  }
}

function addAcceptLanguageHeader(headers) {
  const cookieLangValue = getCookieValue("Abp.Localization.CultureName");
  if (cookieLangValue && headers && !headers.hasOwnProperty('Accept-Language')) {
    headers['Accept-Language'] = cookieLangValue;
  }
}

function addTenantIdHeader(headers) {
  const cookieTenantIdValue = getCookieValue('Abp.TenantId');
  if (cookieTenantIdValue && headers && !headers.hasOwnProperty('Abp.TenantId')) {
    headers['Abp.TenantId'] = cookieTenantIdValue;
  }
}

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const data = response.data
    // if (data.__abp) {
    return handleResponse(data)
    // }
  },
  error => {
    console.log('error', error);
    console.log('error.response', error.response);
    if (error.response && error.response.status !== 200) {
      if (error.response && error.response.status === 401) {
        if (location.pathname === "/login") {
          return false
        } else {
          MessageBox.alert('token过期，请重新登录', '消息提示', {
            confirmButtonText: '确定',
            callback: action => {
              // 授权过期 重新登录
              location.href = `/login`;
            }
          });
        }
        return false
      } else {
        MessageBox.alert(error.response.data.message || '请联系开发人员解决。');
      }
    }
    const data = error.response.data
    // if (data.__abp) {
    handleResponse(data)
    // } else {
    // MessageBox.alert(error.response.statusText, error.response.status)
    // }
    return Promise.reject(error)
  }
)

function handleResponse(data) {
  if (data.result) {
    if (data.success === true) {
      return data.result
    } else {
      MessageBox.alert(data.error.details || data.error.message, data.error.message)
    }
  } else {
    if (data.success === true) {
      return data.result;
    } else {
      if (data.error) {
        MessageBox.alert(data.error.details || data.error.message, data.error.message)
      } else {
        return data;
      }
    }
  }
}

export default service
